rm(list = ls())
options(stringsAsFactors = F)
options(scipen = 200)

library(SummarizedExperiment)
library(TCGAbiolinks)

query <- GDCquery(project = "TCGA-LGG",
                  data.category = "Copy Number Variation",
                  data.type = "Masked Copy Number Segment")
GDCdownload(query,method = "api")
LGG_CNV_download <- GDCprepare(query = query, save = TRUE, save.filename = "LGG_CNV_download.rda")
#读取rda文件
A=load("LGG_CNV_download.rda")
tumorCNV <- eval(parse(text = A))
cliFile="high"

cli1=read.table(cliFile, header=T, sep="\t", check.names=F)
rownames(cli1) <- cli1[,1]
rownames(cli1) <- gsub("\\.", "-", rownames(cli1))
#改名
tumorCNV=tumorCNV[,2:7]
tumorCNV=tumorCNV[,c('Sample','Chromosome','Start','End','Num_Probes','Segment_Mean')]
write.table(tumorCNV,file = 'LGG_CNV.txt',sep = '\t',quote = F,row.names = F)
filename <- 'LGG_CNV.txt'
finalResultName <- 'segment_file.txt'

read_file <- file(filename, "r")
out_file <- file(finalResultName, "a")
while (length(line <- readLines(read_file, n = 1, warn = FALSE)) > 0) {
  data <- strsplit(line, "\\s+")[[1]]
  x <- substr(data[1], 1, 16)  # 从第一个元素中选择前12个字符
  if (x %in% rownames(cli1)) {  # 检查与数据库cli1的行名是否相同
    writeLines(paste(data[1:6], collapse = "\t"), out_file)
    writeLines("", out_file)
  }
}

close(read_file)
close(out_file)
##所有样本
while (length(line <- readLines(read_file, n = 1, warn = FALSE)) > 0) {
  data <- strsplit(line, "\\s+")[[1]]
  x <- substr(data[1], 14, 16)
  if (x == '01A') {
    writeLines(paste(data[1:6], collapse = "\t"), out_file)
    writeLines("", out_file)
  }
}

close(read_file)
close(out_file)

filename <- "snp6.na35.remap.hg38.subset.txt"
finalResultName <- "marker_file.txt"

read_file <- file(filename, "r")
out_file <- file(finalResultName, "a")

while (length(line <- readLines(read_file, n = 1, warn = FALSE)) > 0) {
  data <- strsplit(line, "\\s+")[[1]]
  if (data[6] == 'FALSE') {
    writeLines(paste(data[1:3], collapse = "\t"), out_file)
    writeLines("", out_file)
  }
}

close(read_file)
close(out_file)

rm(list = ls())
options(stringsAsFactors = F)
##输出结果进入gistic2.0在线分析
##BiocManager::install("PoisonAlien/maftools") #建议下载github最新版本的maftools包
library(maftools)
cliFile="low"

cli1=read.table(cliFile, header=T, sep="\t", check.names=F)
cliFile="high"

cli2=read.table(cliFile, header=T, sep="\t", check.names=F)
cli_rows <- rownames(cli1)



#读入GISTIC文件
laml.gistic = readGistic(gisticAllLesionsFile = 'all_lesions.conf_90.txt',
                         gisticAmpGenesFile = 'amp_genes.conf_90.txt', 
                         gisticDelGenesFile = 'del_genes.conf_90.txt', 
                         gisticScoresFile = 'scores.gistic', 
                         isTCGA = T)
cli_rows <- rownames(cli1)
selected_samples <- laml.gistic@Tumor_Sample_Barcode %in% cli_rows

##绘图
#genome plot
gisticChromPlot(gistic = laml.gistic, ref.build = 'hg38')
gisticChromPlot(gistic = laml.gistic[selected_samples, ], ref.build = 'hg38')
